# -*- coding:utf-8 -*-
# @FileName : index.py
# @Time     : 2025/11/25
# @Author   :天空之城
from flask import Flask, render_template, jsonify
import random
from datetime import datetime, timedelta
from collections import Counter

app = Flask(__name__)

# ==========================================
# 1. Mock 数据生成模块 (模拟数据库)
# ==========================================
mock_db = []
models = ['GPT-4', 'GPT-3.5', 'Claude-3', 'Llama-3']
users = ['User_A', 'User_B', 'User_C', 'User_D', 'User_E']


def generate_mock_data():
    """生成过去7天的随机调用记录"""
    data = []
    end_date = datetime.now()
    # 生成 500 条随机记录
    for _ in range(500):
        # 随机回溯 0-7 天
        days_back = random.randint(0, 6)
        log_time = end_date - timedelta(days=days_back)

        record = {
            'user_id': random.choice(users),
            'model': random.choice(models),
            'timestamp': log_time.strftime('%Y-%m-%d')  # 只保留日期用于按天统计
        }
        data.append(record)
    # 按时间排序
    data.sort(key=lambda x: x['timestamp'])
    return data


# 初始化数据
mock_db = generate_mock_data()


# ==========================================
# 2. 路由与逻辑
# ==========================================

@app.route('/')
def index():
    """渲染主页"""
    return render_template('index.html')


@app.route('/api/stats')
def get_stats():
    """API: 返回统计数据"""

    # A. 计算总调用量
    total_calls = len(mock_db)

    # B. 用户调用量 (Top Users)
    user_counts = Counter([log['user_id'] for log in mock_db])
    # 转换为 ECharts 需要的格式: {'categories': [], 'data': []}
    user_data = {
        'categories': list(user_counts.keys()),
        'values': list(user_counts.values())
    }

    # C. 模型调用占比
    model_counts = Counter([log['model'] for log in mock_db])
    # 转换为饼图格式: [{'name': 'GPT-4', 'value': 10}, ...]
    model_data = [{'name': k, 'value': v} for k, v in model_counts.items()]

    # D. 每天的调用量趋势
    date_counts = Counter([log['timestamp'] for log in mock_db])
    # 确保日期连续（可选，这里简单处理，只取存在的日期并排序）
    sorted_dates = sorted(date_counts.keys())
    daily_data = {
        'dates': sorted_dates,
        'values': [date_counts[date] for date in sorted_dates]
    }

    return jsonify({
        'total_calls': total_calls,
        'user_stats': user_data,
        'model_stats': model_data,
        'daily_stats': daily_data
    })


# 模拟新增一次调用的接口（用于演示数据变化）
@app.route('/api/add_call')
def add_call():
    new_record = {
        'user_id': random.choice(users),
        'model': random.choice(models),
        'timestamp': datetime.now().strftime('%Y-%m-%d')
    }
    mock_db.append(new_record)
    return jsonify({'msg': 'success', 'record': new_record})


if __name__ == '__main__':
    app.run(debug=True, port=5000)
